package com.hbm.myimage.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hbm.myimage.entity.Image;
import com.hbm.myimage.entity.ImageTag;
import com.hbm.myimage.entity.Tag;
import com.hbm.myimage.service.ImageService;
import com.hbm.myimage.service.ImageTagService;
import com.hbm.myimage.service.TagService;
import com.hbm.myimage.utils.ListPageUtil;
import com.hbm.myimage.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.var;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.xml.ws.Response;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author testjava
 * @since 2021-11-11
 */
@Api(description="图片管理")//@Api在类上显示在swagger上面
@RestController
@CrossOrigin
@RequestMapping("/myimage/image")
public class ImageController {
    @Autowired
    private ImageService imageService;

    @Autowired
    private TagService tagService;

    @Autowired
    private ImageTagService imageTagService;

    @Autowired
    private HuaweiyunOss huaweiyunOss;

    @PostMapping("/delectImg/{imgId}")
    public Map<String,Object> delectImg( @PathVariable int imgId ){
        HashMap<String, Object> map = new HashMap<>();
        QueryWrapper<ImageTag> tagImgwrapper = new QueryWrapper<>();
        tagImgwrapper.eq("image_id",imgId);
        imageTagService.remove(tagImgwrapper);
        boolean success = imageService.removeById(imgId);
        map.put("success",success);
        return map;

    }

    @GetMapping("/showTag")
    public Map<String,Object> showTag(){
        HashMap<String, Object> map = new HashMap<>();

        List<Tag> tagList = tagService.list(null);
        map.put("tagList",tagList);

        return map;

    }

    @GetMapping("/showAllImgInfo")
    public Map<String,Object> showAllImgInfo(){
        HashMap<String, Object> map = new HashMap<>();

        List<Image> ImgInfo = imageService.list(null);
        map.put("ImgInfo",ImgInfo);

        return map;

    }


    @GetMapping("/showImgInfo/{current}/{limit}")
    public Map<String,Object> showImgInfo(@PathVariable int current,
                                          @PathVariable int limit ){
        HashMap<String, Object> map = new HashMap<>();

        List<ImageAndTagVo> imageAndTagVos = imageService.showImgAndTag();

        List<Object> finalResult=new ArrayList<>();

        int flag=0;
        int i=0;
        while(i<imageAndTagVos.size()){
            List<String> tags=new ArrayList<>();
            HashMap<String, Object> map1 = new HashMap<>();
            String tag = imageAndTagVos.get(i).getTag();
            tags.add(tag);
            int id = imageAndTagVos.get(i).getId();
            String imgTitle = imageAndTagVos.get(i).getImgTitle();
            String imgAdress = imageAndTagVos.get(i).getImgAdress();
            for(int j=1+i;j<imageAndTagVos.size();j++){
                if(imageAndTagVos.get(i).getId()==imageAndTagVos.get(j).getId()){
                    tag = imageAndTagVos.get(j).getTag();
                    tags.add(tag);
                    flag=j;
                    break;
                }

            }
            i=flag+1;
            map1.put("id",id);
            map1.put("imgTitle",imgTitle);
            map1.put("imgAdress",imgAdress);
            map1.put("tags",tags);
            finalResult.add(map1);
            //map.clear();
            flag++;

        }

        ListPageUtil listPageUtil = new ListPageUtil(finalResult, current, limit);
        List data = listPageUtil.getData();
        int totalPage = listPageUtil.getTotalPage();
        int totalCount = listPageUtil.getTotalCount();
        map.put("data",data);
        map.put("total",totalCount);
        map.put("totalPage",totalPage);

        map.put("finalResult",finalResult);
        return map;
    }

    @ApiOperation(value = "展示图片")
    @GetMapping("/showImage/{current}/{limit}")
    public Map<String,Object> showImage( @PathVariable long current, @PathVariable long limit){
        HashMap<String, Object> map = new HashMap<>();

        Page<Image> page = new Page<>(current,limit);
        //分页
        QueryWrapper<Image> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("gmt_modified");
        imageService.page(page, wrapper);

        //查询图片地址
        ArrayList<String> listAdress = new ArrayList<>();

        QueryWrapper<Image> adressWrapper = new QueryWrapper<>();
        adressWrapper.orderByDesc("id");
        List<Image> list = imageService.list(adressWrapper);
        for (Image image : list) {
            listAdress.add(image.getImgadress());
        }

        map.put("listAdress",listAdress);

        long total = page.getTotal();//总记录数
        List<Image> records = page.getRecords(); //数据list集合
        map.put("total",total);
        map.put("records",records);

        List<Image> imageList = imageService.list(null);
        imageList.forEach(System.out::println);
       // map.put("imageList",imageList);

        return map;
    }

    @ApiOperation(value = "根据标题搜索图片")
    @GetMapping("searchByTitle/{titleName}/{current}/{limit}")
    public Map<String,Object> searchByTitle(@PathVariable String titleName, @PathVariable int current,
                                          @PathVariable int limit ){

        HashMap<String, Object> map = new HashMap<>();

        QueryWrapper<Image> wrapper = new QueryWrapper<>();
        wrapper.like("imgtitle",titleName);

        Page<Image> page = new Page<>(current,limit);
        imageService.page(page,wrapper);
        long total = page.getTotal();//总记录数
        List<Image> records = page.getRecords();
        map.put("total",total);
        map.put("records",records);

        return map;
    }

    @ApiOperation(value = "根据tag搜索图片")
    @GetMapping("searchByTag/{tagName}/{current}/{limit}")
    public Map<String,Object> searchByTag(@PathVariable String tagName, @PathVariable int current,
                                          @PathVariable int limit ){
        HashMap<String, Object> map = new HashMap<>();
        QueryWrapper<Tag> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("tag",tagName);
        if(tagService.count(queryWrapper)==0){
            map.put("data","");
            map.put("total",0);
            map.put("totalPage",0);
            return map;
        }
        Tag one = tagService.getOne(queryWrapper);
        Integer tagId = one.getId();
        //map.put("tagId",tagId);

        QueryWrapper<ImageTag> imageTagwrapper = new QueryWrapper<>();
        imageTagwrapper.eq("tag_id",tagId);
        List<ImageTag> imageTags = imageTagService.list(imageTagwrapper);
        //map.put("imageTags",imageTags);

        List<Image> images=new ArrayList<>();
        for (ImageTag imageTag : imageTags) {
            Integer imageId = imageTag.getImageId();
            QueryWrapper<Image> imagewrapper = new QueryWrapper<>();
            imagewrapper.eq("id",imageId);
            Image image = imageService.getOne(imagewrapper);
            images.add(image);
        }
        if(images.size()==0){
            map.put("data","");
            map.put("total",0);
            map.put("totalPage",0);
            return map;
        }

        ListPageUtil listPageUtil = new ListPageUtil(images, current, limit);
        List data = listPageUtil.getData();
        int totalPage = listPageUtil.getTotalPage();
        int totalCount = listPageUtil.getTotalCount();
        map.put("data",data);
        map.put("total",totalCount);
        map.put("totalPage",totalPage);
        //map.put("images",images);

        return map;
    }


    @ApiOperation(value = "保存tag")
    @PostMapping("/saveTag")
    public Map<String,Object> saveTag(@RequestBody String tagName) {
        HashMap<String, Object> map = new HashMap<>();

        Tag tag=new Tag();
        tag.setTag(tagName);

        boolean save = tagService.save(tag);

        map.put("tag",save);

        return map;
    }

    //上传头像的方法
    @ApiOperation(value = "上传图片")
    @PostMapping("/saveImage/{imgTitle}/tagName={tagName}&tagName2={tagName2}")
    public Map<String,Object> uploadOssFile(@PathVariable String imgTitle,@PathVariable String tagName,@PathVariable String tagName2, MultipartFile file){
        HashMap<String, Object> map = new HashMap<>();

        QueryWrapper<Tag> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tag",tagName);
        Tag tag = tagService.getOne(queryWrapper);
        Integer tagId = tag.getId();

        QueryWrapper<Tag> queryWrapper2= new QueryWrapper<>();
        queryWrapper2.eq("tag",tagName2);
        Tag tag2 = tagService.getOne(queryWrapper2);
        Integer tagId2 = tag2.getId();

        //获取上传文件  MultipartFile
        //返回上传到oss的路径image
        String url = imageService.uploadFileAvatar(file);
        if(url==null){
            throw new RuntimeException("图片上传失败！");
        }

        Image image = new Image();
        //String filename = file.getOriginalFilename();
        image.setImgadress(url);
        image.setImgtitle(imgTitle);

        System.out.println("==============url=============");
        System.out.println(url);
        System.out.println("==============url=============");

        //存图片入数据库
        imageService.save(image);

        //获取刚刚存入数据的
        //存imageId
        QueryWrapper<Image> wrapperImg = new QueryWrapper<>();
        wrapperImg.orderByDesc("id");
        wrapperImg.last("limit 1");
        Image imageFinal = imageService.getOne(wrapperImg);
        Integer imageFinalId = imageFinal.getId();

        //存数据进入ImageTag表
        ImageTag tagImage=new ImageTag();
        tagImage.setTagId(tagId);
        tagImage.setImageId(imageFinalId);
        imageTagService.save(tagImage);

        //存数据进入ImageTag表
        ImageTag tagImage2=new ImageTag();
        tagImage2.setTagId(tagId2);
        tagImage2.setImageId(imageFinalId);
        imageTagService.save(tagImage2);


        map.put("url",url);
        return map;
    }


    //上传头像的方法
    @ApiOperation(value = "上传图片")
    @PostMapping("/saveImage/test")
    public Map<String,Object> test(SearchVo searchVo ,MultipartFile file) {
        HashMap<String, Object> map = new HashMap<>();

        //获取上传文件  MultipartFile
        //返回上传到oss的路径image
        String url = imageService.uploadFileAvatar(file);

        String titleName = searchVo.getTitleName();

        Image image = new Image();
        image.setImgtitle(titleName);
        image.setImgadress(url);
        imageService.save(image);

        QueryWrapper<Image> imageWrapper = new QueryWrapper<>();
        imageWrapper.orderByDesc("id");
        imageWrapper.last("limit 1");
        Integer imageId = imageService.getOne(imageWrapper).getId();
        System.out.println(imageId);


        List<String> tagList = searchVo.getTagList();
        for (String tag : tagList) {
            QueryWrapper<Tag> wrapper = new QueryWrapper<>();
            wrapper.eq("tag",tag);
            Integer id = tagService.getOne(wrapper).getId();
            ImageTag imageTag = new ImageTag();
            imageTag.setTagId(id);
            imageTag.setImageId(imageId);
            imageTagService.save(imageTag);
        }


        map.put("url",url);
        return map;
    }

    //上传头像的方法
    @ApiOperation(value = "华为云上传图片")
    @PostMapping("/saveImage/hwyTest")
    public void pic(MultipartFile file) throws IOException {
        String name = file.getOriginalFilename();
        String fileName = file.getOriginalFilename().substring(0, name.lastIndexOf("."));
        System.out.println("fileName------"+fileName);
        boolean isOk = huaweiyunOss.uploadFile1(fileName, file.getInputStream());
        String downloadUrl = huaweiyunOss.getDownloadUrl1(fileName);
        Map<String,Object> map = new HashMap<>();
        map.put("downloadUrl",downloadUrl);
        map.put("fileName",fileName);

        System.out.println("上传成功");
        System.out.println(downloadUrl);
    }

    //上传头像的方法
    @ApiOperation(value = "华为云上传图片111")
    @PostMapping("/saveImage/hwyTest111")
    public void pic1(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        boolean isOk =huaweiyunOss.uploadFile(fileName,file.getInputStream());
        String downloadUrl = huaweiyunOss.getDownloadUrl(fileName);
        System.out.println("上传成功");
        System.out.println(downloadUrl);



    }
    @ApiOperation(value = "华为云上传图片3222")
    @PostMapping("/saveImage/hwyTest13333")
    public byte[] downloadFile(String fileName) {
        try {
            InputStream inputStream = huaweiyunOss.downloadFileInputStream(fileName);
            byte[] bytes = IOUtils.toByteArray(inputStream);
            System.out.println("---------下载成功--------");
            System.out.println(bytes.toString());
            return bytes;
        } catch (Exception e) {
            //log.error("下载文件异常：{}", e.getMessage(), e);
            System.out.println("---------失败--------");
        }
        return null;
    }


}

